import random
from faker import Faker
from datetime import datetime, timedelta

# 初始化Faker
fake = Faker('zh_CN')

def generate_fake_data(field_type, field_info=None):
    """根据字段类型生成假数据"""
    field_info = field_info or {}
    
    # 字符串类型
    if 'char' in field_type or 'text' in field_type:
        if 'name' in field_info.get('name', '').lower():
            return fake.name()
        elif 'email' in field_info.get('name', '').lower():
            return fake.email()
        elif 'phone' in field_info.get('name', '').lower() or 'mobile' in field_info.get('name', '').lower():
            return fake.phone_number()
        elif 'address' in field_info.get('name', '').lower():
            return fake.address()
        elif 'company' in field_info.get('name', '').lower():
            return fake.company()
        elif 'url' in field_info.get('name', '').lower() or 'website' in field_info.get('name', '').lower():
            return fake.url()
        elif 'id_card' in field_info.get('name', '').lower() or 'idcard' in field_info.get('name', '').lower():
            return fake.ssn()
        else:
            # 根据字段长度生成
            length = 10
            if 'varchar' in field_type or 'char' in field_type:
                # 从字段类型中提取长度，如varchar(255)
                try:
                    length = int(field_type.split('(')[1].split(')')[0])
                except:
                    length = 10
            
            # 限制长度
            if length > 100:
                length = 100
            
            return fake.text(length)[:length]
    
    # 整型
    elif 'int' in field_type:
        if 'age' in field_info.get('name', '').lower():
            return random.randint(18, 80)
        elif 'year' in field_info.get('name', '').lower():
            return random.randint(1970, datetime.now().year)
        else:
            return random.randint(0, 10000)
    
    # 浮点型
    elif 'float' in field_type or 'double' in field_type or 'decimal' in field_type:
        if 'price' in field_info.get('name', '').lower() or 'amount' in field_info.get('name', '').lower():
            return round(random.uniform(0, 1000), 2)
        else:
            return round(random.uniform(0, 100), 2)
    
    # 日期类型
    elif 'date' in field_type:
        if 'birth' in field_info.get('name', '').lower():
            # 生成18-80岁的出生日期
            days = random.randint(18*365, 80*365)
            return (datetime.now() - timedelta(days=days)).strftime('%Y-%m-%d')
        else:
            # 生成最近5年内的日期
            days = random.randint(0, 5*365)
            return (datetime.now() - timedelta(days=days)).strftime('%Y-%m-%d')
    
    # 时间类型
    elif 'time' in field_type:
        return fake.time()
    
    # 日期时间类型
    elif 'datetime' in field_type or 'timestamp' in field_type:
        if 'create' in field_info.get('name', '').lower() or 'update' in field_info.get('name', '').lower():
            # 生成最近30天内的日期时间
            days = random.randint(0, 30)
            hours = random.randint(0, 23)
            minutes = random.randint(0, 59)
            seconds = random.randint(0, 59)
            delta = timedelta(days=days, hours=hours, minutes=minutes, seconds=seconds)
            return (datetime.now() - delta).strftime('%Y-%m-%d %H:%M:%S')
        else:
            # 生成最近1年内的日期时间
            days = random.randint(0, 365)
            hours = random.randint(0, 23)
            minutes = random.randint(0, 59)
            seconds = random.randint(0, 59)
            delta = timedelta(days=days, hours=hours, minutes=minutes, seconds=seconds)
            return (datetime.now() - delta).strftime('%Y-%m-%d %H:%M:%S')
    
    # 布尔类型
    elif 'bool' in field_type or 'tinyint(1)' == field_type:
        return random.choice([True, False])
    
    # 枚举类型
    elif 'enum' in field_type:
        # 从字段类型中提取枚举值，如enum('male','female')
        try:
            enum_values = field_type.split('(')[1].split(')')[0].split(',')
            enum_values = [v.strip("'\"") for v in enum_values]
            return random.choice(enum_values)
        except:
            return ''
    
    # 默认返回空字符串
    else:
        return ''

def generate_fake_row(schema):
    """根据表结构生成一行假数据"""
    row = {}
    for field in schema:
        # 跳过自增主键
        if field.get('is_primary') and 'auto_increment' in field.get('extra', ''):
            continue
        
        # 生成假数据
        row[field['name']] = generate_fake_data(field['type'], field)
    
    return row

def generate_fake_batch(schema, count=100):
    """生成一批假数据"""
    return [generate_fake_row(schema) for _ in range(count)]